<template>
  <view class="emergency_box">
    <view class="app-title ac">
      <view class="fl" @click="back">
        <image class="back" src="/static/img/back.png"></image>
      </view>
      {{ "创建工单" }}
    </view>

    <!-- <view class="top-bg" v-if="!param"></view> -->
    <view style="height: 140upx"></view>
    <view class="emergency_body_box">
      <view class="body_box_content">
        <scroll-view scroll-y="true" class="scroll-Y">
          <view class="list-area">
            <u-cell-group>
              <view class="list-item-title">基本信息</view>
              <u-cell-item
                title="工单类别:"
                required
                :value="
                  listOrderData.woCategory == ''
                    ? '请选择'
                    : listOrderData.woCategory
                "
                @click="
                  selece_type = 'orderType';
                  show_picker = true;
                  columns = workOrderType;
                  label_name = 'value';
                  value_name = 'code';
                "
              >
              </u-cell-item>
              <!-- 			<u-field :disabled="true" v-model="listOrderData.woCategory" label="工单类别:"
								placeholder="请填写"></u-field> -->
              <!-- 	<u-field :disabled="true" v-model="listOrderData.woSn" label="工单编号:"
								placeholder="请填写"></u-field>
							<u-field :disabled="true" v-model="listOrderData.releaseTime" label="发布时间:"
								placeholder="请填写"></u-field> -->
              <!-- 		<u-cell-item title="发布时间:"
								:value="listOrderData.releaseTime == '' ? '请选择' : listOrderData.releaseTime" @click="
							  typeid==2&&editStatus ?show_date = true :'';
								date_type = 'relaseTime';">
							</u-cell-item> -->
              <view class="rowClass">
                <u-cell-item
                  required
                  title="专业"
                  :value="
                    listOrderData.major == ''
                      ? '请选择'
                      : returChName(listOrderData.major, workProfession)
                  "
                  @click="
                    selece_type = 'major';
                    show_picker = true;
                    columns = workProfession;
                    label_name = 'value';
                    value_name = 'code';
                  "
                >
                </u-cell-item>
                <u-cell-item
                  required
                  title="线路"
                  :value="
                    listOrderData.woLineName == ''
                      ? '请选择'
                      : listOrderData.woLineName
                  "
                  @click="
                    selece_type = 'line';
                    show_picker = true;
                    columns = lineTree;
                    label_name = 'name';
                    value_name = 'idK';
                  "
                >
                </u-cell-item>
              </view>
              <view class="rowClass">
                <u-cell-item
                  required
                  title="机构:"
                  :value="
                    listOrderData.managementOrgName == ''
                      ? '请选择'
                      : listOrderData.managementOrgName
                  "
                  @click="showORG()"
                >
                </u-cell-item>
                <u-cell-item
                  v-if="false"
                  title="工单负责人"
                  :value="
                    listOrderData.woLeaderName == ''
                      ? '请选择'
                      : listOrderData.woLeaderName
                  "
                  @click="
                    selece_type = 'leader';
                    show_picker = true;
                    columns = leaderOptions;
                    label_name = 'name';
                    value_name = 'idK';
                  "
                >
                </u-cell-item>
              </view>
              <u-cell-item
                required
                title="所在地点"
                :value="
                  listOrderData.locationName == '' ||
                  listOrderData.locationName == 'null'
                    ? '请选择'
                    : listOrderData.locationName
                "
                @click="show_station = true"
              >
              </u-cell-item>
              <u-cell-item
                title="施工区域"
                :value="
                  listOrderData.constructArea == ''
                    ? '请选择'
                    : listOrderData.constructArea
                "
                @click="show_Area = true"
              >
              </u-cell-item>
            </u-cell-group>
            <u-cell-item
              title="开始时间:"
              required
              :value="
                listOrderData.startTime == ''
                  ? '请选择'
                  : listOrderData.startTime
              "
              @click="
                show_date = true;
                date_type = 'startTime';
              "
            >
            </u-cell-item>
            <u-cell-item
              title="结束时间:"
              required
              :value="
                listOrderData.endTime == '' ? '请选择' : listOrderData.endTime
              "
              @click="
                show_date = true;
                date_type = 'endTime';
              "
            >
            </u-cell-item>
            <u-field
              :label-width="70"
              input-align="right"
              v-model="listOrderData.constructContent"
              label="施工内容:"
              placeholder="请填写"
              type="textarea"
            ></u-field>
            <u-cell-group>
              <u-cell-item
                :border-top="true"
                :title="'作业任务' + taskNum"
                arrow-direction="down"
                :arrow="false"
              >
                <view slot="right-icon" class="tools">
                  <!-- <text @click="viewTask">查看/执行</text> -->
                  <text @click="editTask()"> 修改</text>
                </view>
              </u-cell-item>
            </u-cell-group>
            <u-field
              :label-width="100"
              input-align="right"
              v-model="listOrderData.influenceArea"
              label="施工影响范围:"
              placeholder="请填写"
              type="textarea"
            ></u-field>
            <u-cell-group>
              <u-cell-group v-if="false">
                <u-cell-item
                  title="作业人数"
                  arrow-direction="down"
                  :arrow="false"
                >
                  <!-- typeid!=2?true:!editStatus -->
                  <view slot="right-icon"
                    ><u-number-box
                      :disabled="true"
                      v-model="listOrderData.personNumber"
                    ></u-number-box
                  ></view>
                </u-cell-item>
              </u-cell-group>
              <u-cell-item
                v-if="false"
                title="作业人员"
                :value="listOrderData.constructPersonName"
                @click="show_people = false"
              >
              </u-cell-item>
              <u-cell-item
                :title="'工器具' + toolNum"
                arrow-direction="down"
                :arrow="false"
              >
                <view slot="right-icon" class="tools">
                  <text @click="viewtool">查看</text
                  ><text @click="edittool()"> | 修改</text>
                </view>
              </u-cell-item>
              <!-- <u-field v-model="listOrderData.constructPersonName" label="点单编号:"
								placeholder="请填写"></u-field>
							<u-cell-item title="点单开始时间:"
								:value="listOrderData.taskStartTime == '' ? '请选择' : listOrderData.taskStartTime" @click="
								show_date = true;
								date_type = 'orderStartTime';">
							</u-cell-item>

							<u-cell-item title="点单结束时间:"
								:value="listOrderData.taskStartTime == '' ? '请选择' : listOrderData.taskStartTime" @click="
								show_date = true;
								date_type = 'orderEndTime';">
							</u-cell-item> -->
              <!-- <view class="list-item-title">工单审核</view> -->
              <!-- 		<u-field :label-width='100' input-align="right" v-model="listOrderData.completenote"
								label="工单完成情况:" placeholder="请填写" type="textarea"></u-field>
							<view class="complete">
								<view>
									<view>
										<text>完成度</text>
									</view>
									<view>
										<u-slider v-model="value" :use-slot="true">
											<view class="">
												<view class="badge-button">
													{{value}}
												</view>
											</view>
										</u-slider>
									</view>
								</view>
								<hr />
							</view> -->
              <!-- <u-field v-model="listOrderData.statusName" label="质量确认人:" placeholder="请填写"></u-field> -->
              <u-field
                :disabled="true"
                class="lastField"
                v-model="listOrderData.woState"
                label="工单状态:"
                placeholder=""
              ></u-field>
            </u-cell-group>
          </view>
        </scroll-view>
        <view class="footer">
          <!-- 	<u-button :custom-style="customStyle" type="primary" size="medium" :ripple="true"
						@click="newSave">保存</u-button> -->
          <u-button
            :custom-style="customStyle"
            type="primary"
            size="medium"
            :ripple="true"
            @click="crearedOrder"
            >创建</u-button
          >
        </view>
      </view>
    </view>

    <u-select
      v-model="show_picker"
      :list="columns"
      :label-name="label_name"
      :value-name="value_name"
      @confirm="onConfirm"
      @cancel="onCancel"
    >
    </u-select>
    <u-picker
      v-model="show_date"
      mode="time"
      :params="params"
      @confirm="setDate"
      @cancel="onCancel"
    ></u-picker>
    <SelectStation
      v-if="show_station"
      :stationName="listOrderData.locationName"
      :station="station_options"
      @close="show_station = false"
      @setStation="setStation"
    ></SelectStation>
    <!-- 		<u-select v-model="teamName_select" mode="mutil-column-auto" :label-name="label_name" :value-name="value_name"
			:list="reeByOrgnum" @confirm="confirmSet"></u-select> -->
    <SelectArea
      v-if="show_Area"
      :constructAreaName="listOrderData.constructArea"
      :constructArea="workArea"
      @close="show_Area = false"
      @setArea="setArea"
    ></SelectArea>
    <!-- 施工区域 -->

    <!-- 选择机构 -->
    <ljs-treeChoose
      :data="departList"
      @getChooseValue="orgchange"
      @close="orgcancle"
      v-if="orgShow"
    />
    <!-- 工器具 -->
    <toolDevice
      @passToolsData="acceptToolsData"
      :toolConfig="toolConfig"
      :show.sync="toolsDevicShow"
    ></toolDevice>
    <!-- 任务详情 -->
    <taskDetail
      v-if="taskShow"
      @passTaskData="acceptTaskData"
      :taskConfig="taskConfig"
      :taskParam="taskParam"
      :show.sync="taskShow"
    ></taskDetail>
  </view>
</template>

<script>
import { PMS_DICT_CONTROLLER, WORK_CONTROLLER } from "../../api/pms";
import toolDevice from "../../components/myWork/viewWork/toolDevice.vue";
import taskDetail from "../../components/myWork/viewWork/task.vue";
import SelectStation from "../../components/myWork/viewWork/selectStation";
import SelectPeople from "../../components/myWork/viewWork/selectPeople.vue";
import SelectArea from "../../components/myWork/viewWork/selectArea.vue";
import { mapState } from "vuex";
export default {
  components: {
    toolDevice,
    SelectStation,
    taskDetail,
    SelectArea,
  },
  props: {},
  data() {
    return {
      value: 20,
      departList: [],
      orgShow: false,
      toolConfig: {
        title: "工器具详情",
        type: "view",
        data: [],
      },
      taskConfig: {
        title: "工作详情",
        type: "view",
        data: [],
      },
      toolsData: [],
      station_options: [],
      people_options: [],
      customStyle: {
        // backgroundColor: "#15c6ac",
        width: "40%",
      },
      detailData: {},
      listOrderData: {
        woCategory: "",
      },
      columns: [],
      type: true,
      show_picker: false,
      show_date: false,
      label_name: "",
      value_name: "",
      selece_type: "", // 下拉框类型
      toolsDevicShow: false, // 工器具 弹框
      taskShow: false, // 具体任务详情
      show_station: false,
      show_people: false,
      show_Area: false,
      teamName_select: false, // 显示班组级联框
      leaderOptions: [], //工单人员列表
      operationBtn: [], // 操作按钮
      params: {
        year: true,
        month: true,
        day: true,
        hour: true,
        minute: true,
        second: true,
      },
      taskParam: {
        stations: [],
        startTime: "", // 工单开始时间
        woState: "",
        typeid: "",
      },
      woSn: "",
      typeid: "",
      pmsWoDetailed: [
        {
          taskType: "其他任务",
          taskYearName: "",
          taskName: "",
          equID: "",
          equName: "",
          equTypeID: "",
          equTypeName: "",
          orderNumber: "",
          taskLocation: "",
          taskLocationName: "",
          endTime: "",
          startTime: "",
          detailedContent: "",
        },
      ], // 任务详情
      pmsWoTools: [], // 工器具
      remark: "", // 处理意见
      editStatus: true,
      paifaStatus: false,
      referce: false,
      approveFlag: true,
      creared: "",
      modelshow: false,
      checkRemark: "",
      contentStyle: {
        borderBottom: "1px solid red",
      },
      uploadMediaType: "image",
      uploadformData: {},
      uploadData: [],
      uploadUrl: "",
      control: false,
      showControl: false,
      modelContent: {
        padding: "15px",
      },
      titleStyle: {
        paddingTop: "16px",
        fontWeight: 600,
      },
      description: "",
      config: {
        pmsEquControl: "",
        pmsNfcShow: "",
        pmsScanCode: "",
        woSn: "",
      },
      taskNum: "",
      toolNum: "",
    };
  },
  computed: {
    ...mapState([
      "userInfo",
      "workOrderType",
      "workProfession",
      "workOrderState",
      "lineTree",
      "reeByOrgnum",
      "workArea",
    ]),
  },
  watch: {},
  onShow() {},
  async onLoad(options) {
    this.typeid = options.typeid;
  },
  async created() {
    this.listOrderData.managementOrgName = this.userInfo?.org?.name;
    this.listOrderData.major = this.returChName(
      this.userInfo?.roles[0].major,
      this.workProfession
    );
    this.listOrderData.managementOrg = this.userInfo?.org?.num;
    if (this.lineTree.length == 1) {
      console.log("this.lineTree", this.lineTree);
      this.listOrderData.woLineName = this.lineTree[0].name;
      this.listOrderData.woLine = this.lineTree[0].idK;
      this.handleLine();
    }
  },
  methods: {
    returChName(value, options) {
      let name;
      let filterArr = options.filter((item) => item.code == value);
      filterArr.length ? (name = filterArr[0].value) : (name = value);
      // options.filter(item=>item.code==value)[0].value

      return name;
    },
    formatDate(time) {
      var date = new Date(time);
      var year = date.getFullYear(),
        month = date.getMonth() + 1, //月份是从0开始的
        day = date.getDate(),
        hour = date.getHours(),
        min = date.getMinutes(),
        sec = date.getSeconds();
      var newTime =
        year +
        "-" +
        (month < 10 ? "0" + month : month) +
        "-" +
        (day < 10 ? "0" + day : day) +
        " " +
        (hour < 10 ? "0" + hour : hour) +
        ":" +
        (min < 10 ? "0" + min : min) +
        ":" +
        (sec < 10 ? "0" + sec : sec);

      return newTime;
    },
    async crearedOrder() {
      this.listOrderData.releaseTime = this.formatDate(new Date());
      await this.newSave();
      // this.$store.commit('setSpeechUpValue', '')
      // setTimeout(() => {
      // 	this.$store.commit('setSpeechUpValue', 12345)
      // }, 10000)
    },
    getNameByOrgId() {
      if (this.listOrderData.managementOrg) {
        this.fetch(
          "get",
          this.$store.state.baseUrl + WORK_CONTROLLER.GET_NAME_BY_ORGID,
          {
            num: this.listOrderData.managementOrg,
          }
        ).then((res) => {
          if (res?.success) {
            this.leaderOptions = res?.data;
          }
        });
      } else {
        this.leaderOptions = [];
      }
    },
    showORG() {
      let self = this;
      this.orgShow = true;
      self.departList = self.reeByOrgnum.map((org) => self.mapTree(org));
    },
    mapTree(org) {
      const haveChildren =
        Array.isArray(org.children) && org.children.length > 0;
      return {
        id: org.orgnum,
        label: org.text,
        openTag: false,
        choose: false,
        children: haveChildren ? org.children.map((i) => this.mapTree(i)) : [],
      };
    },
    orgchange(org, items) {
      this.listOrderData.managementOrgName = items[items.length - 1].label;
      this.listOrderData.managementOrg = items[items.length - 1].id;
      setTimeout(() => {
        this.orgcancle();
      }, 500);
      this.getNameByOrgId();
      this.listOrderData.woLeaderName = "";
      this.listOrderData.woLeaderId = "";
    },
    orgcancle() {
      this.orgShow = false;
    },
    setStation(obj) {
      this.listOrderData.locationName = obj.name.toString();
      this.listOrderData.location = obj.id.toString();
      this.show_station = false;
    },

    setArea(obj) {
      this.listOrderData.constructArea = obj.name.toString();
      // this.listOrderData.constructPerson = obj.id;
      this.show_Area = false;
    },

    checkWoRequire() {
      if (
        !this.listOrderData.major ||
        !this.listOrderData.woLineName ||
        !this.listOrderData.managementOrgName ||
        !this.listOrderData.locationName ||
        !this.listOrderData.woCategory ||
        !this.listOrderData.startTime ||
        !this.listOrderData.endTime
      ) {
        uni.showToast({
          title: "请填写必填项",
          icon: "none",
        });
        return false;
      } else {
        return true;
      }
    },
    async newSave() {
      if (!this.checkWoRequire()) return;
      if (
        new Date(this.listOrderData.startTime).getTime() >
        new Date(this.listOrderData.endTime).getTime()
      ) {
        uni.showToast({
          title: "开始时间不能大于结束时间",
          icon: "none",
        });
        return;
      }
      let param = {
        pmsWoDetailedWorkDOList: this.pmsWoDetailed,
        pmsWoToolsDOList: this.pmsWoTools,
        pmsWoinforDOList: this.listOrderData,
      };
      await this.fetch(
        "post",
        this.$store.state.baseUrl + WORK_CONTROLLER.POST_SAVE_PmsInfo,
        param
      ).then((res) => {
        if (res.success) {
          uni.showToast({
            title: "保存成功",
            icon: "none",
          });
          this.back();
        } else {
          uni.showToast({
            title: "保存失败",
            icon: "none",
          });
        }
      });
    },

    onConfirm(item) {
      switch (this.selece_type) {
        case "orderType":
          this.listOrderData.woCategory = item[0].label;
          // this.listOrderData.orderTypeCode = item[0].value
          break;
        case "line":
          this.listOrderData.woLineName = item[0].label;
          this.listOrderData.woLine = item[0].value;
          this.handleLine(item); // 根据 地铁线路获取对应的站
          this.listOrderData.locationName = "";
          this.listOrderData.location = "";
          break;
        case "major":
          // this.listOrderData.major = item[0].label
          this.listOrderData.major = item[0].value;
          // this.listOrderData.professionCode = item[0].value
          break;
        case "constrareaName":
          this.listOrderData.constructArea = item[0].label;
          // this.listOrderData.constrareaCode = item[0].value
          break;
        case "leader":
          this.listOrderData.woLeaderName = item[0].label;
          this.listOrderData.woLeaderId = item[0].value;
          break;
        default:
      }
      this.onCancel();
    },
    onCancel() {
      this.show_picker = false;
      this.show_date = false;
      this.show_station = false;
    },
    handleLine(obj) {
      if (this.listOrderData.woLine) {
        this.fetch(
          "get",
          this.$store.state.baseUrl + PMS_DICT_CONTROLLER.GET_NAME_BY_LINEID,
          {
            lineId: obj ? obj[0].value : this.listOrderData.woLine,
            orgNum: this.listOrderData.managementOrg,
          }
        ).then((res) => {
          if (res?.success) {
            this.station_options = res?.data;
          }
        });
      } else {
        this.station_options = [];
      }
    },
    setDate(obj) {
      let str = `${obj.year}-${obj.month}-${obj.day} ${obj.hour}:${obj.minute}:${obj.second}`;
      this.listOrderData[this.date_type] = str;
      this.onCancel();
    },
    // 查看工器具
    viewtool() {
      this.toolsDevicShow = true;
      this.toolConfig.type = "view";
      this.toolConfig.title = "工器具详情";
      this.toolConfig.data = JSON.parse(JSON.stringify(this.pmsWoTools));
    },
    // 修改工器具
    edittool() {
      this.toolsDevicShow = true;
      this.toolConfig.type = "edit";
      this.toolConfig.title = "修改工器具";
      this.toolConfig.data = JSON.parse(JSON.stringify(this.pmsWoTools));
    },
    acceptToolsData(val) {
      this.listOrderData.PmsWoTools = val;
      this.pmsWoTools = val;
      let totalNum = 0;
      val.forEach((item) => {
        if (item.demandNumber) {
          totalNum += item.demandNumber;
        }
      });
      if (val.length && totalNum) {
        this.toolNum = `(${totalNum}件)`;
      }
    },
    // 查看任务
    viewTask() {
      // this.taskShow = true
      this.taskConfig.type = "view";
      this.taskConfig.title = "任务详情";
      this.taskConfig.data = JSON.parse(JSON.stringify(this.pmsWoDetailed));
      this.taskParam.typeid = this.typeid;
      this.taskParam.woState = this.listOrderData.woState;
      this.taskParam.woSn = this.woSn;
      this.config.woSn = this.woSn;
      this.config.woState = this.listOrderData.woState;
    },
    // 修改任务
    editTask() {
      this.taskShow = true;
      this.taskConfig.type = "create";
      (this.taskConfig.title = "修改任务"),
        (this.taskConfig.data = JSON.parse(JSON.stringify(this.pmsWoDetailed)));
      this.taskParam.stations = this.listOrderData.location;
      this.taskParam.startTime = this.listOrderData.startTime;
      this.taskParam.woState = this.listOrderData.woState;
      this.taskParam.typeid = this.typeid;
      this.taskParam.woSn = this.woSn;
    },
    async acceptTaskData(val) {
      this.listOrderData.PmsWoDetailed = val;
      this.pmsWoDetailed = val;
      if (val.length) {
        this.taskNum = `(${val.length}项)`;
      }
      // await this.newSave()
      this.taskConfig.data = JSON.parse(JSON.stringify(this.pmsWoDetailed));
    },
    back() {
      uni.navigateTo({
        url: `/pages/index/index`,
      });
    },
  },
};
</script>

<style scoped lang="less">
/deep/.htz-image-upload-Item {
  width: 70px;
  height: 70px;
}

.tips {
  color: red;
  font-size: 12px;
  padding: 5px 10px;
  border-bottom: 1px solid #f0f0f0;
}

/deep/.u-model__footer {
  border-top: 1px solid #f0f0f0;
}

.u-radio-group {
  padding: 10px 8px 0;
}

.rowClass {
  display: flex;
  flex-direction: row;

  &:nth-child(2) {
    // padding-left: 5px!important;
  }
}

.lastField::after {
  border-bottom: 0px;
}

/deep/ .u-cell {
  padding: 10px 2px !important;
}

.u-field {
  padding: 10px 2px 10px 8px !important;
}

/deep/.u-label {
  flex: 0 0 auto !important;
}

/deep/.u-cell--required:before {
  left: 2px;
}

/deep/.u-cell_title {
  color: #333;
  padding-left: 8px;
}

/deep/.u-cell__value {
  padding: 0 4px 0 8px;
}

.content {
  height: 100vh;
  width: 100%;
  // display: flex;
  // flex-direction: column;
  padding: 0 0rpx;
  overflow: hidden;
  // position: absolute;
}

.emergency_box {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #fff;
}

.body_box {
  width: 95%;
  margin: 0 auto;
  background: #ffffff;
  position: relative;
  z-index: 100;
  height: calc(100vh - 100px);
  top: -100px;
  border-radius: 10px;
  padding: 10px 0;
}

.body_box_content {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.scroll-Y {
  flex: 1;
  height: 0;
  padding: 0 20rpx;
}

.emergency_body_box {
  width: 100%;
  margin: 0 auto;
  height: calc(100% - 70px);
  // .body_box_content{
  // 	padding: 0 20rpx;
  // }
}

.footer {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  flex-wrap: wrap;
  // margin-top: 10rpx;
  border-radius: 0, 0, 10px, 10px;
  border-top: 1px solid #f1f1f1;
  padding: 10px 20rpx 10px;
  box-shadow: 5px -1px 5px #f6f6f6;

  /deep/.u-btn {
    // margin: 10rpx 5%;
    // margin-right: 30rpx;
    width: 30% !important;
  }

  :last-child {
    // margin-right: 0px;
  }
}

.app-title {
  position: fixed;
  top: 0;
  width: 100%;
  z-index: 99;
}

.list-area {
  hr {
    border: 0;
    border-top: 1px solid #f2f3f6;
  }

  .list-item-title {
    background-color: #f5f5f5;
    height: 70rpx;
    line-height: 70rpx;
    padding-left: 30rpx;
    font-size: 30rpx;
    color: #a7a7a7;
    font-weight: bold;
  }
}

:deep(.uni-input-input) {
  text-align: right;
}

/deep/.u-input__input {
  height: 100%;
}

.tools {
  color: #2979ff;

  text:nth-of-type(1) {
    padding-right: 6px;
  }

  text:nth-of-type(2) {
    padding-left: 0px;
  }
}

.wrap {
  padding: 30rpx;
}

.badge-button {
  padding: 4rpx 6rpx;
  background-color: #e4393c;
  color: #fff;
  border-radius: 10rpx;
  font-size: 22rpx;
  line-height: 1;
}

.complete {
  > view:nth-of-type(1) {
    padding: 26rpx 32rpx 26rpx 0;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;

    :nth-child(2) {
      // flex: 1;
      width: 60%;
    }
  }
}
</style>
